package com.ruyuan.seckilling.publish.async.listener;

import com.alibaba.fastjson.JSON;
import com.ruyuan.seckilling.common.ChannelKey;
import com.ruyuan.seckilling.publish.async.event.DownloadEvent;
import com.ruyuan.seckilling.publish.async.event.WriteToDiskEvent;
import com.ruyuan.starter.async.AsyncContext;
import com.ruyuan.starter.async.BossEventBus;
import com.ruyuan.starter.async.anno.Channel;
import com.ruyuan.starter.async.event.BaseEvent;
import com.ruyuan.starter.async.listener.EventListener;
import com.ruyuan.starter.async.thread.ExecutorService;
import com.ruyuan.starter.jedis.CacheSupport;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author zhonghuashishan
 */
@Slf4j
@Component
@Channel(ChannelKey.CHANNEL_DOWNLOAD)
public class DownloadEventListener implements EventListener<DownloadEvent> {

    @Autowired
    private BossEventBus bossEventBus;

    @Autowired
    private ExecutorService executorService;

    @Autowired
    private CacheSupport cacheSupport;

    @Override
    public boolean accept(BaseEvent event) {
        return event instanceof DownloadEvent;
    }

    @Override
    public void onEvent(DownloadEvent event, AsyncContext eventContext) {
        executorService.execute(ChannelKey.CHANNEL_DOWNLOAD, () -> {
            String staticPageContent = cacheSupport.get(event.getStaticPageId());
            log.info("第1步，下载页面, event={}", JSON.toJSONString(event));

            WriteToDiskEvent e = new WriteToDiskEvent();
            e.setPageLogId(event.getPageLogId());
            e.setStaticPageId(event.getStaticPageId());
            e.setStaticPagePath(event.getStaticPagePath());
            e.setStaticPageContent(staticPageContent);

            bossEventBus.publish(ChannelKey.CHANNEL_WRITE_TO_DISK, e, null);
        });
    }
}
